import React, { useEffect, useRef } from 'react';
import { Card, Spin, Empty } from 'antd';

interface DataPoint {
  time: string;
  value: number;
}

interface LineChartProps {
  title: string;
  data: DataPoint[];
  loading?: boolean;
  height?: number;
  color?: string;
  yAxisLabel?: string;
  xAxisLabel?: string;
}

const LineChart: React.FC<LineChartProps> = ({
  title,
  data,
  loading = false,
  height = 300,
  color = '#1890ff',
  yAxisLabel = '',
  xAxisLabel = '',
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (!loading && data.length > 0 && canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      
      if (ctx) {
        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 设置边距
        const margin = { top: 20, right: 20, bottom: 30, left: 40 };
        const width = canvas.width - margin.left - margin.right;
        const chartHeight = canvas.height - margin.top - margin.bottom;
        
        // 找到数据的最大值和最小值
        const maxValue = Math.max(...data.map(d => d.value));
        const minValue = Math.min(...data.map(d => d.value));
        const valueRange = maxValue - minValue || 1; // 避免除以零
        
        // 绘制坐标轴
        ctx.beginPath();
        ctx.strokeStyle = '#e0e0e0';
        ctx.moveTo(margin.left, margin.top);
        ctx.lineTo(margin.left, chartHeight + margin.top);
        ctx.lineTo(width + margin.left, chartHeight + margin.top);
        ctx.stroke();
        
        // 绘制Y轴标签
        ctx.fillStyle = '#666';
        ctx.font = '12px Arial';
        ctx.textAlign = 'right';
        ctx.textBaseline = 'middle';
        
        const yTickCount = 5;
        for (let i = 0; i <= yTickCount; i++) {
          const y = margin.top + chartHeight - (i / yTickCount) * chartHeight;
          const value = minValue + (i / yTickCount) * valueRange;
          
          ctx.fillText(value.toFixed(1), margin.left - 5, y);
          
          // 绘制网格线
          ctx.beginPath();
          ctx.strokeStyle = '#f0f0f0';
          ctx.moveTo(margin.left, y);
          ctx.lineTo(width + margin.left, y);
          ctx.stroke();
        }
        
        // 绘制X轴标签
        const xTickCount = Math.min(data.length, 5); // 最多显示5个标签，避免拥挤
        const xStep = Math.max(1, Math.floor(data.length / xTickCount));
        
        ctx.textAlign = 'center';
        ctx.textBaseline = 'top';
        
        for (let i = 0; i < data.length; i += xStep) {
          const x = margin.left + (i / (data.length - 1)) * width;
          ctx.fillText(data[i].time, x, chartHeight + margin.top + 5);
        }
        
        // 绘制数据线
        if (data.length > 1) {
          ctx.beginPath();
          ctx.strokeStyle = color;
          ctx.lineWidth = 2;
          
          // 移动到第一个点
          const firstX = margin.left;
          const firstY = margin.top + chartHeight - ((data[0].value - minValue) / valueRange) * chartHeight;
          ctx.moveTo(firstX, firstY);
          
          // 连接后续点
          for (let i = 1; i < data.length; i++) {
            const x = margin.left + (i / (data.length - 1)) * width;
            const y = margin.top + chartHeight - ((data[i].value - minValue) / valueRange) * chartHeight;
            ctx.lineTo(x, y);
          }
          
          ctx.stroke();
          
          // 绘制数据点
          data.forEach((point, i) => {
            const x = margin.left + (i / (data.length - 1)) * width;
            const y = margin.top + chartHeight - ((point.value - minValue) / valueRange) * chartHeight;
            
            ctx.beginPath();
            ctx.fillStyle = color;
            ctx.arc(x, y, 3, 0, Math.PI * 2);
            ctx.fill();
          });
        }
        
        // 绘制坐标轴标签
        if (yAxisLabel) {
          ctx.save();
          ctx.translate(10, margin.top + chartHeight / 2);
          ctx.rotate(-Math.PI / 2);
          ctx.textAlign = 'center';
          ctx.fillText(yAxisLabel, 0, 0);
          ctx.restore();
        }
        
        if (xAxisLabel) {
          ctx.textAlign = 'center';
          ctx.fillText(xAxisLabel, margin.left + width / 2, canvas.height - 5);
        }
      }
    }
  }, [data, loading, color, yAxisLabel, xAxisLabel]);

  return (
    <Card title={title} style={{ marginBottom: 16 }}>
      {loading ? (
        <div style={{ height, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Spin />
        </div>
      ) : data.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" style={{ height, display: 'flex', flexDirection: 'column', justifyContent: 'center' }} />
      ) : (
        <canvas ref={canvasRef} width={600} height={height} style={{ width: '100%', height: 'auto' }} />
      )}
    </Card>
  );
};

export default LineChart; 